package com.doghome.news.service.impl;

import java.util.Date;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.doghome.news.dao.CommentMapper;
import com.doghome.news.dao.NewsMapper;
import com.doghome.news.entity.News;
import com.doghome.news.service.NewsService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;

@Service
@Transactional
public class NewsServiceImpl implements NewsService {
	
	@Autowired
	private NewsMapper newsMapper;
	
	@Autowired
	private CommentMapper commentMapper;

	
	@Override
	public PageInfo<News> newsByPage(Integer tid, String title, int pageNum, int pageSize) {
		PageHelper.startPage(pageNum,pageSize);
		return new PageInfo<News>(newsMapper.selectAll(tid, title));
	}


	@Override
	@Transactional(propagation = Propagation.SUPPORTS)
	public News showNewsById(Integer nid) {
		return newsMapper.selectByPrimaryKey(nid);
	}


	@Override
	public boolean addNews(News news) {
		news.setNcreatedate(new Date());
		return newsMapper.insert(news) == 1 ? true : false;
	}


	@Override
	public boolean editNews(News news) {
		news.setNmodifydate(new Date());
		return newsMapper.updateByPrimaryKeySelective(news) == 1 ? true : false;
	}


	@Override
	public boolean delNews(int nid) {
		try {
			commentMapper.deleteByNid(nid);
			int count = newsMapper.deleteByPrimaryKey(nid);
			if(count == 1) {
				return true;
			}
		}catch (Exception e) {
			throw new RuntimeException("删除评论失败！");
		}
		return false;
	}


	@Override
	public int countNewsById(Integer tid) {
		return newsMapper.countByTid(tid);
	}

}
